#include "HighPrecisionTimer.h"

void HighPrecisionTimer::start()
{
	QueryPerformanceCounter(&ltick);
	elapsed = 0;
	isRunning = true;
	tloop = new thread(&HighPrecisionTimer::loop, this);
	tloop->detach();
}

void HighPrecisionTimer::pause()
{
	isPaused = true;
}

void HighPrecisionTimer::resume()
{
	isPaused = false;
}

void HighPrecisionTimer::reset()
{
	elapsed = 0;
}

void HighPrecisionTimer::stop()
{
	TerminateThread(tloop, 0);
	isRunning = false;
}

void HighPrecisionTimer::loop()
{
	while (1)
	{
		QueryPerformanceCounter(&tick);
		QueryPerformanceFrequency(&freq);
		if (!isPaused)
		{
			elapsed = elapsed + ((tick.QuadPart - ltick.QuadPart) / (double)freq.QuadPart);
			ltick = tick;
		}
		else
		{
			ltick = tick;
		}
		Sleep(1);
		//this_thread::sleep_for(chrono::nanoseconds(100));
	}
}

void HighPrecisionTimer::setcheckpoint()
{
	checkpoint = elapsed;
}

float HighPrecisionTimer::getElapsed()
{
	return elapsed * 1000;
}

float HighPrecisionTimer::getElapsedReset()
{
	float ret = getElapsed();
	elapsed = 0;
	return ret;
}

float HighPrecisionTimer::getElapsedFromCheckpoint()
{
	return elapsed - checkpoint;
}
